import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
// 配置路由规则
const constRouter = [
  // 重定向
  {
    path: '',
    redirect: "/login"
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    redirect: '/home',
    component: () => import('@/layout/layout.vue'),
    children: [
      {
        meta:{
          title: 'ホームページ',
          requiresAuth: true
        },
        path: '/home',
        name: 'home',
        component: () => import('@/views/HomeView.vue'),
        
      }
    ]
  },
  {
    path: "/user",
    component: ()=>  import('@/layout/layout.vue'),
    redirect: "/user/update",
    meta: {
      title: "利用者変更",
      requiresAuth: true
    },
    children: [
      {
        path: "/user/update",
        component: ()=> import("@/views/user/Update.vue"),
        name: "update",
         meta: {
          title: "利用者情報変更",
          requiresAuth: true
        }
      },
      {
        path: "/user/detailList",
        component: ()=> import("@/views/user/DetailList.vue"),
        name: "detailList",
         meta: {
          title: "利用者変更履歴一覧",
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: "/card",
    component: ()=>  import('@/layout/layout.vue'),
    redirect: "/card/apply",
    meta: {
      title: "カード変更",
      requiresAuth: true
    },
    children: [
      {
        path: "/card/apply",
        component: ()=> import("@/views/card/Apply.vue"),
        name: "card",
         meta: {
          title: "カード利用状況",
          requiresAuth: true
        }
      }
    ]
  }

]
// 创建路由
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  // 使用路路由规则常量
  routes: constRouter
})

// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = !!localStorage.getItem('token');

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next({ name: 'login' });
    } else {
      next();
    }
  } else {
    next();
  }
})
// 导出router
export default router